package com.gullmall.ware.service.impl;

import com.gullmall.common.constant.WareConstant;
import com.gullmall.common.utils.R;
import com.gullmall.ware.entity.vo.MergeVo;
import com.gullmall.ware.entity.PurchaseDetailEntity;
import com.gullmall.ware.entity.vo.PurchaseDoneVo;
import com.gullmall.ware.entity.vo.PurchaseItemDoneVo;
import com.gullmall.ware.service.PurchaseDetailService;
import com.gullmall.ware.service.WareSkuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gullmall.common.utils.PageUtils;
import com.gullmall.common.utils.Query;

import com.gullmall.ware.dao.PurchaseDao;
import com.gullmall.ware.entity.PurchaseEntity;
import com.gullmall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;


@Service("purchaseService")
@Transactional
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    /**
     * 查询未领取(新建)的采购单
     */
    @Override
    public PageUtils unReceiveList(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", WareConstant.PurchaseStatusEnum.CREATED.getCode())
                        .or()
                        .eq("status", WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        );

        return new PageUtils(page);
    }


    //合并采购需求
    @Override
    public R mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> items = mergeVo.getItems();
        //验证传过来的采购项是否有效
        List<PurchaseDetailEntity> checkPurchaseDetail = purchaseDetailService.listByIds(items);
        if (checkPurchaseDetail == null || checkPurchaseDetail.size() <= 0) {
            return R.error("采购项无效");
        }
        //传过来的采购项存在,则验证他们的状态是否是【新建】或【分配】状态.不是则不能修改
        for (PurchaseDetailEntity p : checkPurchaseDetail) {
            if (!WareConstant.PurchaseDetailStatusEnum.CREATED.getCode().equals(p.getStatus())
            &&!WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode().equals(p.getStatus())) {
                return R.error("采购项id【" + p.getId() + "】已被【领取】或【完成】");
            }
        }
         //新建采购单
        if (purchaseId == null || purchaseId == 0) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //采购单状态[0新建，1已分配，2正在采购，3已完成，4采购失败]
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            PurchaseEntity purchaseEntity = this.getById(purchaseId);
            if (!WareConstant.PurchaseStatusEnum.CREATED.getCode().equals(purchaseEntity.getStatus())
                    && !WareConstant.PurchaseStatusEnum.ASSIGNED.getCode().equals(purchaseEntity.getStatus())) {
                return R.error("采购单只能是【新建】或【已分配状态】");
            }
        }
        //合并采购需求,到指定采购单上
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(item -> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            //改为已分配的状态
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());
        purchaseDetailService.updateBatchById(purchaseDetailEntities);


        return R.ok();
    }

    @Override
    public R receive(List<Long> purchaseIds) {
        //1 确认采购单是 新建 或 已分配状态
        //2 改变采购单的状态
        //3 改变采购需求的状态
        //4 TODO  分配到的采购员才可领取采购单

        List<PurchaseEntity> purchaseEntities = this.listByIds(purchaseIds);
        if (purchaseEntities == null || purchaseEntities.size() <= 0) {
            return R.error("没有该采购单");
        }
        List<PurchaseEntity> filterPurchaseEntities = purchaseEntities.stream().filter(p -> {
            //过滤状态不符合的采购单
            return WareConstant.PurchaseStatusEnum.CREATED.getCode().equals(p.getStatus())
                    || WareConstant.PurchaseStatusEnum.ASSIGNED.getCode().equals(p.getStatus());
        }).map(m -> {
            //新建,否则全量更新
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(m.getId());
            //改变状态为【已领取】
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());
        if (filterPurchaseEntities == null || filterPurchaseEntities.size() <= 0) {
            return R.error("没有符合条件的采购单");
        }

        List<Long> filterPurchaseIds = filterPurchaseEntities.stream()
                .map(m -> m.getId()).collect(Collectors.toList());


        List<PurchaseDetailEntity> detailEntities = purchaseDetailService.list(
                new QueryWrapper<PurchaseDetailEntity>().in("purchase_id", filterPurchaseIds));

        if (detailEntities == null || detailEntities.size() <= 0) {
            return R.error("该采购单下没有采购需求");
        }
        List<PurchaseDetailEntity> filterDetailEntities = detailEntities.stream().filter(f -> {
            //状态[0新建，1已分配，2正在采购，3已完成，4采购失败]
            //过滤不符合的采购需求,只能是0或1
            if (WareConstant.PurchaseDetailStatusEnum.CREATED.getCode().equals(f.getStatus())
                    || WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode().equals(f.getStatus())) {
                return true;
            }
            return false;
        }).map(m -> {
            //新建,否则全量更新
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(m.getId());
            //改变状态为 2正在采购
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        if (filterDetailEntities == null || filterDetailEntities.size() <= 0) {
            return R.error("没有符合条件的采购需求");
        }
        //更新wms_purchase的状态
        this.updateBatchById(filterPurchaseEntities);
        //更新wms_purchase_detail的状态
        purchaseDetailService.updateBatchById(filterDetailEntities);

        return R.ok();
    }

    //完成采购计划 成功 或 失败
    @Override
    public R done(PurchaseDoneVo purchaseDoneVo) {
        boolean isAllDone = true;//标志位,采购项全部完成为true,有1个失败为false

        //1,改变采购项的状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailList = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(item.getItemId());
            if (WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode().equals(item.getStatus())) {
                //采购成功
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode());

            } else {//采购失败
                isAllDone = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FAILED.getCode());
            }
            purchaseDetailList.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailList);

        //2,改变采购单的状态
        //如果采购项全部成功,则采购单状态改为成功
        //如果有1个采购项失败,则采购单状态改为【有异常】
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
        purchaseEntity.setStatus(isAllDone ? WareConstant.PurchaseStatusEnum.FINISHED.getCode() : WareConstant.PurchaseStatusEnum.FAILED.getCode());
        this.updateById(purchaseEntity);

        //3,将成功采购的 采购项 纳入库存
        //过滤出 采购成功 的采购项的id
        List<Long> purchaseDetailDoneIds = purchaseDetailList.stream()
                .filter(f -> WareConstant.PurchaseDetailStatusEnum.FINISHED.getCode().equals(f.getStatus()))
                .map(m -> m.getId()).collect(Collectors.toList());

        if (purchaseDetailDoneIds.size() <= 0) return R.error("没有符合要求的采购项");

        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(purchaseDetailDoneIds);
        if (purchaseDetailEntities == null || purchaseDetailEntities.size() <= 0) return R.error("没有符合要求的采购项");

        Integer code = wareSkuService.addStock(purchaseDetailEntities).getCode();//为0则入库成功

        return R.ok();
    }

}